﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;
using PanoramaApp1.ViewModels;
using System.Xml;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using System.IO.IsolatedStorage;
using Microsoft.Phone.BackgroundAudio;

namespace PanoramaApp1
{


    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
        }

        List<Song> songs;

        public void getRadioMenu(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                App.ViewModel.LoadData(e.Result);
                Regex radioMenuRegex = new Regex(@"class=""_radioMenu(\s[^""]*)?""\s+id=""_cat(?<id>\d+)""[^>]+>(?<title>[^<+]+)</a>");
                MatchCollection radioMenuMatches = radioMenuRegex.Matches(e.Result);

                foreach (Match match in radioMenuMatches)
                {
                    RadioMenu radioMenu = new RadioMenu()
                    {
                        Header = match.Groups["title"].ToString(),
                        ItemsSource = App.ViewModel.Channels[Convert.ToInt32(match.Groups["id"].ToString())]
                    };

                    radioMenu.ItemsList.SelectionChanged += new SelectionChangedEventHandler(listChannels_changed);

                    zingRadioPanorama.Items.Add(radioMenu);
                }
            }
        }

        public void listChannels_changed(object sender, SelectionChangedEventArgs e)
        {
            LongListSelector itemsList = sender as LongListSelector;
            if (itemsList == null || itemsList.SelectedItem == null) return;
            ItemViewModel item = itemsList.SelectedItem as ItemViewModel;
            WebClient webClient = new WebClient();
            webClient.Headers["user-agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13";
            webClient.Headers["accept"] = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";

            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getRadioPlaylist);
            webClient.DownloadStringAsync(new Uri("http://mp3.zing.vn" + item.LineThree));
        }

        public void getRadioPlaylist(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                string html = e.Result;

                Regex xmlUrlRegex = new Regex(@"<param.+xmlURL=(?<url>[^&]+)");

                Match match = xmlUrlRegex.Match(html);
                if (!match.Success)
                {
                    xmlUrlRegex = new Regex(@"xmlURL:'(?<url>[^']+)'");
                    match = xmlUrlRegex.Match(html);
                }

                if (!match.Success)
                {
                    MessageBox.Show("Không tìm thấy link xml trong album!");
                    return;
                }

                WebClient webClient = new WebClient();
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getListSong);
                webClient.DownloadStringAsync(new Uri(match.Groups["url"].ToString()));
            }
        }

        public void getListSong(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                string html = e.Result;
                
                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                using (IsolatedStorageFileStream file = new IsolatedStorageFileStream("playlist.xml",FileMode.Create,storage))
                {
                    StreamWriter stream = new StreamWriter(file);
                    stream.Write(html);
                    stream.Close();
                }
                
                
                BackgroundAudioPlayer.Instance.Play();
            }
        }

        private PanoramaItem createPanoramaItemStyle1(string Header)
        {
            PanoramaItem item = new PanoramaItem() { Header = Header };

            return item;
        }


        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                WebClient webClient = new WebClient();
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getRadioMenu);
                webClient.DownloadStringAsync(new Uri("http://mp3.zing.vn/radio"));
            }
        }
    }
}
